package com.woniu.teachmall04.controller;

import com.woniu.teachmall04.entity.Goods;
import com.woniu.teachmall04.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/goods")
public class GoodsController {
    @Autowired
    private GoodsService goodsService;

    // 商品详情页
    @GetMapping("/{id}")
    public String detail(@PathVariable Integer id, Model model) {
        Goods goods = goodsService.getById(id);
        if(goods == null || !"Y".equals(goods.getStatus())) {
            return "redirect:/";
        }
        model.addAttribute("goods", goods);
        return "goods/detail";
    }

    // 商品列表页
    @GetMapping("/list")
    public String list(@RequestParam(defaultValue = "1") int page,
                       @RequestParam(required = false) Integer categoryId,
                       @RequestParam(required = false) String keyword,
                       @RequestParam(required = false) BigDecimal minPrice,
                       @RequestParam(required = false) BigDecimal maxPrice,
                       Model model) {
        List<Goods> goodsList = goodsService.getByPage(page, categoryId, keyword, minPrice, maxPrice);
        long totalPages = goodsService.getTotalPages(categoryId, keyword, minPrice, maxPrice);

        model.addAttribute("goodsList", goodsList);
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPages", totalPages);
        model.addAttribute("categoryId", categoryId);
        model.addAttribute("keyword", keyword);
        model.addAttribute("minPrice", minPrice);
        model.addAttribute("maxPrice", maxPrice);

        return "goods/list";
    }

    // 首页热门商品和新品
    @GetMapping("/featured")
    @ResponseBody
    public Map<String, List<Goods>> featured() {
        Map<String, List<Goods>> result = new HashMap<>();
        result.put("hottest", goodsService.getHottest());
        result.put("newest", goodsService.getNewest());
        return result;
    }
}